<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind">
			<uni-forms-item name="title" label="标题" required>
				<uni-easyinput placeholder="标题" v-model="formData.title" trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="author" label="作者">
				<uni-easyinput placeholder="请输入作者名称" v-model="formData.author" trim="right"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="avatar" label="封面">
				<uni-file-picker file-mediatype="image" :auto-upload="false" @select="handleFileSelect" return-type="object" v-model="formData.avatar"></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item name="content" label="内容" required>
				<!-- <uni-easyinput placeholder="文章内容" v-model="formData.content" trim="right"></uni-easyinput> -->
				<contentEditor v-model:value="formData.content"></contentEditor>
			</uni-forms-item>
			<uni-forms-item name="view_count" label="阅读量">
				<uni-easyinput placeholder="阅读数量" type="number" v-model="formData.view_count"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="select" label="推荐">
				<switch @change="binddata('select', $event.detail.value)" :checked="formData.select"></switch>
			</uni-forms-item>
			<uni-forms-item name="publish_date" label="时间">
				<uni-datetime-picker return-type="timestamp" v-model="formData.publish_date"></uni-datetime-picker>
			</uni-forms-item>
			<uni-forms-item name="status" label="状态">
				<uni-data-checkbox v-model="formData.status" :localdata="formOptions.status_localdata"></uni-data-checkbox>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px">
					<button class="uni-button" style="width: 100px">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
import { validator } from '@/js_sdk/product_news/list.js';
import contentEditor from './contentEditor.vue';
import { uploadFileToDir } from '../product_wallpaper/utils.js';

const db = uniCloud.database();
const dbCmd = db.command;
const dbCollectionName = 'product_news';

function getValidator(fields) {
	let result = {};
	for (let key in validator) {
		if (fields.includes(key)) {
			result[key] = validator[key];
		}
	}
	return result;
}

export default {
	components: { contentEditor },
	data() {
		let formData = {
			title: '',
			author: '',
			avatar: null,
			content: '',
			view_count: 55,
			select: null,
			publish_date: null,
			status: 1
		};
		return {
			formData,
			formOptions: {
				status_localdata: [
					{
						value: 0,
						text: '草稿箱'
					},
					{
						value: 1,
						text: '已发布'
					}
				]
			},
			rules: {
				...getValidator(Object.keys(formData))
			}
		};
	},
	onLoad(e) {
		if (e.id) {
			const id = e.id;
			this.formDataId = id;
			this.getDetail(id);
		}
	},
	onReady() {
		this.$refs.form.setRules(this.rules);
	},
	methods: {
		/**
		 * 手动上传文件
		 */
		handleFileSelect(fileInfo) {
			uploadFileToDir(fileInfo, 'news', (fileUrl) => {
				this.formData.avatar = fileUrl;
			});
		},
		/**
		 * 验证表单并提交
		 */
		submit() {
			uni.showLoading({
				mask: true
			});
			this.$refs.form
				.validate()
				.then((res) => {
					return this.submitForm(res);
				})
				.catch(() => {})
				.finally(() => {
					uni.hideLoading();
				});
		},

		/**
		 * 提交表单
		 */
		submitForm(value) {
			// 使用 clientDB 提交数据
			return db
				.collection(dbCollectionName)
				.doc(this.formDataId)
				.update(value)
				.then((res) => {
					uni.showToast({
						title: '修改成功'
					});
					this.getOpenerEventChannel().emit('refreshData');
					setTimeout(() => uni.navigateBack(), 500);
				})
				.catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					});
				});
		},

		/**
		 * 获取表单数据
		 * @param {Object} id
		 */
		getDetail(id) {
			uni.showLoading({
				mask: true
			});
			db.collection(dbCollectionName)
				.doc(id)
				.field('title,author,avatar,content,view_count,select,publish_date,status')
				.get()
				.then((res) => {
					const data = res.result.data[0];
					if (data) {
						this.formData = data;
					}
				})
				.catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					});
				})
				.finally(() => {
					uni.hideLoading();
				});
		}
	}
};
</script>
